#!/bin/bash
source /home/shell/util.sh
source /home/shell/jenkins/jenkins-util.sh

update_site=https://jenkins-zh.gitee.io/update-center-mirror/tsinghua/update-center.json
update_base_site=https://mirrors.huaweicloud.com/jenkins/plugins

install_jenkins

# 设置端口
read -p "请输入Jenkins端口[8080]:" jenkins_port
jenkins_port=${jenkins_port:-"8080"};

source /etc/profile.d/java.sh

sed -ri "s/8080/"$jenkins_port"/" /etc/init.d/jenkins
sed -ri "s/HTTP_PORT=8080/HTTP_PORT="$jenkins_port"/" /etc/default/jenkins

# 设置JDK路径
sed -i "s#PATH=/bin:/usr/bin:/sbin:/usr/sbin#PATH=/bin:/usr/bin:/sbin:/usr/sbin:/opt/jdk/bin#" /etc/init.d/jenkins

/lib/systemd/systemd-sysv-install enable jenkins
systemctl daemon-reload
systemctl restart jenkins

while [ true ]; do
  if [[ -n "$(tail /var/log/jenkins/jenkins.log|grep 'Jenkins is fully up and running')" ]]; then
    break;
  fi
  if [[ -n "$(tail -100 /var/log/jenkins/jenkins.log|grep 'java.net.BindException: Address already in use')" ]]; then
    printFail "java.net.BindException: Address already in use,Failed to bind to 0.0.0.0/0.0.0.0:${jenkins_port}，安装程序退出！"
    exit;
  fi
  if [[ -n "$(tail -100 /var/log/jenkins/jenkins.log|grep 'Jetty shutdown successfully')" ]]; then
    printFail "服务安装失败，安装程序退出！"
    exit;
  fi
  loadMsg "Jenkins服务启动中..."
  sleep 1s 
done




# sed -ri "s/updates.jenkins.io/mirrors.tuna.tsinghua.edu.cn/g" /var/lib/jenkins/updates/default.json
rm -rf /var/lib/jenkins/updates/default.json

for item in ${jenkins_plugins[*]}; do
  download /var/lib/jenkins/plugins/${item}.jpi ${update_base_site}/${item}/latest/${item}.hpi
done

# 设置插件中心
sed -ri "s#<url>https://updates.jenkins.io/update-center.json</url>#<url>"$update_site"</url>#" /var/lib/jenkins/hudson.model.UpdateCenter.xml
sed -ri "s/-Djava.awt.headless=true/-Djava.awt.headless=true -Dhudson.model.DownloadService.noSignatureCheck=true/g" /etc/default/jenkins
systemctl daemon-reload
systemctl restart jenkins


# 设置防火墙
firewall-addport $jenkins_port

loadmsg_time=0;
while [ -z "`tail /var/log/jenkins/jenkins.log|grep 'Jenkins is fully up and running'`" ]; do
  loadMsg "Jenkins即将完成安装..."
  sleep 1s 
done

# 显示信息
printInfo "=====================jenkins====================="
printInfo "后台地址：http://$host_addr:$jenkins_port"
printInfo "初始密码："`cat /var/lib/jenkins/secrets/initialAdminPassword`
printInfo "update site：`cat /var/lib/jenkins/hudson.model.UpdateCenter.xml|grep url|sed -r 's#.*<url>(.*)</url>#\1#g'`"
printInfo "日志位置：/var/log/jenkins/jenkins.log"
printInfo "配置文件：/etc/init.d/jenkins"
printInfo "配置文件：/etc/default/jenkins"
printInfo "插件目录：/var/lib/jenkins/plugins/"
printInfo "缓存目录：/var/cache/jenkins"
printInfo "war包文件：/usr/share/jenkins/jenkins.war"
printInfo "=====================jenkins====================="